import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Form, Table, Popconfirm } from 'antd';
import { eventTrack } from '@/utils/track';
import { utils } from 'vv-frontend-components';
import isEmpty from 'lodash/isEmpty';
import moment from 'moment';
import { history } from 'umi';
import LinkTo from '@/components/LinkTo';
// AuthComponent AuthCode权限控制
// import AuthCode from '@/utils/auth/AuthCode';
import QuickEntry from '@/components/QuickEntry/QuickEntry'; // 快速入职
import Pagination from '@/components/Pagination';
import TableFilter from '@/components/TableFilter';
import CandidateSearchForm from './SearchForm';
import AddCandidate from './AddCandidate'; // 添加候选人
import Filter from './Filter'; // 发起用人部门筛选
import './index.less';
// 状态色
const dictColor = {
    applying: '#40A9FF', // 申请中
    apply_failed: '#F5222D', // "申请未通过"
    apply_success: '#52C41A', // 申请通过
    be_pending: '#40A9FF', // 待定
    eliminated: '#F5222D', // 淘汰
    entry_cancel: '#F5222D', // 取消入职
    entry_success: '#52C41A', // 已入职
    offer_accepted: '#40A9FF', // 已接受
    offer_refused: '#F5222D', // 已拒绝
    offer_sended: '#40A9FF', // 已发送
    pass: '#52C41A', // 通过
    wait_for_beginning: '#d8d8d8', // "待开始"
    wait_for_processing: '#d8d8d8', // 待处理
    entry_doing: '#40A9FF', // 入职中"
    interview_cancel: '#d8d8d8' // 面试取消
};
// 应聘职位
// const renderOption = postTypeData => {
//     return postTypeData.map(item => {
//         return <Option value={item.dictValue}>{item.dictName}</Option>;
//     });
// };

// 删除列表
const confirm = async (candidateCode, dispatch, fetchList) => {
    await dispatch({
        type: 'common/candidateDelete',
        payload: {
            candidateCode
        },
        success: () => {
            // 成功刷新页面
            fetchList({ pageNo: 1 });
        }
    });
    // message.success('click on Yes');
};
// 发起offer
const getOffer = ({ dispatch, record }) => {
    dispatch({
        type: 'common/featchApply',
        payload: {
            companyId: record.companyId // 候选人公司id
        },
        callback: res => {
            history.push({
                pathname: '/personal/portal/flow/mine/list/apply',
                query: {
                    action: 'edit',
                    formDeploymentId: res.formDeploymentId,
                    processDeploymentId: res.processDeploymentId,
                    templateId: res.id,
                    templateName: res.templateName, // 后台返回值
                    talentId: record.candidateCode,
                    talentName: record.talentName
                }
            });
        }
    });
};
const getSexName = key => {
    if (key === '1') {
        return <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />;
    }
    if (key === '2') {
        return <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />;
    }
    return '';
};
// 列表项
const columns = ({
    stageList,
    scheduleList,
    dispatch,
    setVisible,
    // setentryVisible,
    setCandicode,
    setTalentCurent,
    setRecruitCurent,
    // query,
    candidateStage,
    candidateState,
    typeJump,
    fetchList
}) => [
    {
        title: '姓名',
        dataIndex: 'talentName',
        key: 'talentName',
        width: 160,
        fixed: 'left',
        render(text, record) {
            const { candidateCode, isInterview, isApplyOffer } = record;
            const path =
                typeJump === 'mine'
                    ? '/personal/portal/recruit/candidate/detail'
                    : '/office/personnelManagement/recruit/candidate/detail';
            return (
                <div style={{ display: 'flex' }}>
                    <LinkTo
                        // 埋点
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personal_my_recruit_candidate_detail_click',
                                eventProps: { label: '我的候选人-候选人详情', tabs: '我管理的候选人' }
                            });
                            history.push(url);
                        }}
                        to={path}
                        query={{
                            candidateCode,
                            isInterview: isInterview.toString(),
                            isApplyOffer: isApplyOffer.toString()
                        }}
                        className="marginR"
                        style={{
                            display: 'inline-block',
                            maxWidth: 200,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        title={text}
                    >
                        {text}
                    </LinkTo>
                    {getSexName(record.talentSex)}
                </div>
            );
        }
    },
    {
        title: '应聘职位',
        dataIndex: 'recruitPost',
        key: 'recruitPost',
        width: 160,
        fixed: 'left'
    },
    {
        title: '公司',
        dataIndex: 'companyName',
        key: 'companyName',
        width: 200
    },
    {
        title: '添加候选时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 200,
        sorter: () => {}
        // render(text, record) {
        //     return <span>{record.startTime}</span>;
        // }
    },
    {
        title: '阶段',
        dataIndex: 'candidateStageValue',
        key: 'candidateStageValue',
        filters: stageList,
        // ...filterValuesCfg,
        filteredValue: candidateStage,
        filterMultiple: false,
        filterDropdown: filterProps => <TableFilter {...filterProps} />,
        width: 180
    },
    {
        title: '状态',
        dataIndex: 'candidateStateValue',
        key: 'candidateStateValue',
        filters: scheduleList,
        filteredValue: candidateState,
        filterMultiple: false,
        filterDropdown: filterProps => <TableFilter {...filterProps} />,
        width: 150,
        render(text, record) {
            return (
                <span>
                    <span
                        className="manaCircle"
                        style={{
                            backgroundColor: dictColor[record.candidateState]
                        }}
                    ></span>
                    {text}
                </span>
            );
        }
    },
    {
        title: <span style={{ whiteSpace: 'nowrap' }}>招聘负责</span>,
        dataIndex: 'candidateLeaderName',
        // width: 200,
        key: 'candidateLeaderName',
        render(text) {
            return <span style={{ whiteSpace: 'nowrap' }}>{text}</span>;
        }
    },
    {
        title: '操作',
        dataIndex: '',
        key: '',
        width: 250,
        fixed: 'right',
        render(text, record) {
            return (
                <div>
                    {record.isDepartmentChoose ? (
                        <a
                            className="marginR dividingline"
                            onClick={e => {
                                e.preventDefault();
                                setVisible(true);
                                setCandicode(record.candidateCode);
                                setTalentCurent(record.talentName);
                                setRecruitCurent(record.recruitName);
                            }}
                        >
                            用人部门筛选
                        </a>
                    ) : null}
                    {record.isInterview ? (
                        <LinkTo
                            // 埋点
                            onClick={async (e, url) => {
                                await eventTrack({
                                    eventName: 'personal_my_recruit_candidate_operator_click',
                                    eventProps: {
                                        tabs: '我管理的候选人',
                                        label: '我的候选人-发起面试'
                                    }
                                });
                                history.push(url);
                            }}
                            to={
                                typeJump === 'mine'
                                    ? '/personal/portal/recruit/interview/add'
                                    : '/office/personnelManagement/recruit/interview/add'
                            }
                            query={{
                                candidateCode: record.candidateCode,
                                type: 'type0'
                            }}
                            className="marginR dividingline"
                        >
                            发起面试
                        </LinkTo>
                    ) : null}
                    {record.isSearchInterview ? (
                        <LinkTo
                            // 埋点
                            onClick={async (e, url) => {
                                await eventTrack({
                                    eventName: 'personal_my_recruit_candidate_operator_click',
                                    eventProps: {
                                        tabs: '我管理的候选人',
                                        label: '我的候选人-查看面试'
                                    }
                                });
                                history.push(url);
                            }}
                            to={
                                typeJump === 'mine'
                                    ? '/personal/portal/recruit/interview'
                                    : '/office/personnelManagement/recruit/interview'
                            }
                            query={{
                                candidateName: record.talentName
                            }}
                            className="marginR dividingline"
                        >
                            查看面试
                        </LinkTo>
                    ) : null}
                    {record.isWatchOffer ? (
                        <LinkTo
                            // 埋点
                            onClick={async (e, url) => {
                                await eventTrack({
                                    eventName: 'personal_my_recruit_candidate_operator_click',
                                    eventProps: {
                                        tabs: '我管理的候选人',
                                        label: '我的候选人-查看offer'
                                    }
                                });
                                history.push(url);
                            }}
                            // to="/personal/recruit/offer/detail"
                            to={`${
                                typeJump === 'mine' ? '/personal/portal' : '/office/personnelManagement'
                            }/recruit/offer/detail`}
                            query={{ offerCode: record.offerCode }}
                            className="marginR dividingline"
                        >
                            查看offer
                        </LinkTo>
                    ) : null}
                    {record.isDeleteCandidate ? (
                        <Popconfirm
                            title="你确定删除吗?"
                            onConfirm={() => {
                                confirm(record.candidateCode, dispatch, fetchList);
                            }}
                            // onCancel={cancel}
                            okText="确定"
                            cancelText="取消"
                        >
                            <a href="#" className="marginR dividingline">
                                删除
                            </a>
                        </Popconfirm>
                    ) : null}
                    {record.isApplyOffer ? (
                        <LinkTo
                            onClick={async (e, url) => {
                                await eventTrack({
                                    eventName: 'personal_my_recruit_candidate_operator_click',
                                    eventProps: {
                                        tabs: '我管理的候选人',
                                        label: '我的候选人-申请offer'
                                    }
                                });
                                history.push(url);
                                getOffer({ dispatch, record });
                            }}
                            className="marginR dividingline"
                        >
                            申请offer
                        </LinkTo>
                    ) : null}
                    {/* {record.isEntry ? (
                        <a
                            className="marginR dividingline"
                            onClick={e => {
                                e.preventDefault();
                                setentryVisible(true);
                                setCandicode(record.candidateCode);
                            }}
                        >
                            快速入职
                        </a>
                    ) : null} */}
                </div>
            );
        }
    }
];
const List = ({ activeKey, form, loading, manage, common, dispatch, location, route, addVisible, setaddVisible }) => {
    // 我的候选人与候选人管理公用组件
    // mine: 我的候选人  company: 候选人管理
    const { path } = route;
    let typeJump = '';
    if (path === '/office/personnelManagement/recruit/candidate') {
        typeJump = 'company';
    } else if (path === '/personal/portal/recruit/candidate') {
        typeJump = 'mine';
    } else {
        throw new Error('未找到路径！请检查');
    }
    // 按钮权限控制
    // const { authCode } = new AuthCode(route.code);
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const { pagination, manageList: tableData, orderBy } = manage;
    const { stageList, scheduleList } = common;
    const [collapsed, setCollapsed] = useState(!!(query.collapsed && query.collapsed === '1') || '1');
    const [candidateStage, setCandidateStage] = useState(
        query.candidateStage && typeof query.candidateStage === 'string' ? [query.candidateStage] : []
    );
    const [candidateState, setCandidateState] = useState(
        query.candidateState && typeof query.candidateState === 'string' ? [query.candidateState] : []
    );
    const [candicode, setCandicode] = useState(''); // 更新当前候选人candidatecode
    const [talentCurent, setTalentCurent] = useState(''); // 更新当前候选人姓名
    const [recruitCurent, setRecruitCurent] = useState(''); // 更新当前候选人recruitName
    const [visible, setVisible] = useState(false); // 监听用人筛选模态框
    // const [addVisible, setaddVisible] = useState(false); // 监听添加候选人模态框
    const [entryVisible, setentryVisible] = useState(false); // 监听快速入职模态框
    // 获取登陆人公司id
    const user = localStorage.getItem('user');
    const { companyId } = user ? JSON.parse(user) : {};
    const userCompanyId = companyId;
    // 获取参数
    const { getFieldsValue } = form;
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const {
            candidateName,
            recruitCode,
            companyId: companyIds,
            addtime
            // candidateLeaderId = ''//新需求删除该字段
        } = getFieldsValue();
        // 接口传参参数
        const payload = {
            candidateStage,
            candidateState,
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            orderByField: orderBy,
            // 高级搜索字段
            candidateName,
            recruitCode,
            companyId: companyIds || userCompanyId,
            beginTime: !isEmpty(addtime) ? addtime[0].format('YYYY-MM-DD 00:00:00') : '',
            endTime: !isEmpty(addtime) ? addtime[1].format('YYYY-MM-DD 23:59:59') : ''
            // candidateLeaderId: candidateLeaderId.split('-')[0]
        };
        return payload;
    };
    // 接口请求
    const fetchList = (ctx = {}) => {
        // 方法自动获取高级搜索表单参数
        const { candidateLeaderId = '' } = getFieldsValue();
        const { pageNo = null } = ctx;
        if (typeJump === 'mine') {
            dispatch(
                deepTrim({
                    type: 'manage/fetchManageList',
                    payload: getSearchData(pageNo)
                })
            );
        } else {
            dispatch(
                deepTrim({
                    type: 'manage/fetchCompanyManageList',
                    payload: {
                        ...getSearchData(pageNo),
                        candidateLeaderId: candidateLeaderId.split('-')[0]
                    }
                })
            );
        }
    };

    // 排序功能
    const tableChange = async (newPagination, filters, sorter) => {
        let orderBys;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'createTime') {
                sorterField = 'create_time';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBys = `${sorterField} ${order}`;
        }
        setCandidateStage(filters && filters.candidateStageValue ? filters.candidateStageValue : []);
        setCandidateState(filters && filters.candidateStateValue ? filters.candidateStateValue : []);
        await dispatch({
            type: 'manage/save',
            payload: {
                orderBy: orderBys || '',
                candidateStage: (filters && filters.candidateStageValue) || [], // 筛选阶段
                candidateState: (filters && filters.candidateStateValue) || [], // 筛选状态
                pagination: {
                    ...manage.pagination,
                    ...newPagination,
                    current: 1
                }
            }
        });
        history.push({
            query: {
                ...query,
                candidateStage:
                    filters && filters.candidateStageValue && filters.candidateStageValue.length > 0
                        ? filters.candidateStageValue[0]
                        : '',
                candidateState:
                    filters && filters.candidateStateValue && filters.candidateStateValue.length > 0
                        ? filters.candidateStateValue[0]
                        : ''
            }
        });
    };

    const paginationChange = newPagination => {
        dispatch({
            type: 'manage/save',
            payload: {
                pagination: {
                    ...manage.pagination,
                    ...newPagination
                }
            }
        });
    };

    // 加载阶段、状态筛选列数据
    useEffect(() => {
        dispatch({
            type: 'common/fetchStageList',
            payload: {
                dictCode: 'candidateStageType'
            }
        });
        dispatch({
            type: 'common/fetchscheduleList',
            payload: {
                dictCode: 'candidateStateType'
            }
        });
    }, []);
    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'manage/save',
                payload: {
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    },
                    orderBy: '',
                    candidateState: [],
                    candidateStage: [],
                    manageList: []
                }
            });
        },
        []
    );
    // 初始化查询参数，用于 URL 参数化
    const initFields = React.useCallback(() => {
        const { beginTime, endTime } = query;
        // if (query.companyId) {
        //     setCollapsed(false);
        // }
        form.setFieldsValue({
            addtime: beginTime ? [moment(beginTime), moment(endTime)] : '',
            candidateStage: query.candidateStage || [],
            candidateState: query.candidateState || [],
            candidateName: query.candidateName || '',
            recruitCode: query.recruitCode,
            companyId: query.companyId || undefined,
            candidateLeaderId: query.candidateLeaderId ? `${query.candidateLeaderId}-` : undefined
        });
    }, [form]);

    const handleSubmit = e => {
        const { eType } = e;
        console.log(eType, '+++++eType');
        const { candidateLeaderId } = getFieldsValue();
        const { candidateStage: candidateStage1, candidateState: candidateState1 } = query;
        history.push({
            query: {
                ...query,
                ...getSearchData(),
                candidateStage: candidateStage1,
                candidateState: candidateState1,
                candidateLeaderId: typeJump === 'mine' ? '' : (candidateLeaderId || '').split('-')[0]
            }
        });
        fetchList({ pageNo: 1 });
        // 埋点
        eventTrack({
            eventName:
                eType === 'submit'
                    ? 'personal_my_recruit_candidate_search_click'
                    : 'personal_my_recruit_candidate_reset_click',
            eventProps: {
                tabs: eType === 'submit' ? '我的候选人-搜索' : '我的候选人-清空',
                key_words: eType === 'submit' ? JSON.stringify(getFieldsValue()) : null
            }
        });
    };

    React.useEffect(() => {
        initFields();
    }, []);

    const isFirstRun = useRef(true);
    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        if (activeKey === '1') {
            fetchList();
        }
    }, [orderBy, pagination.pageSize, pagination.current, candidateStage, candidateState]);
    // 切换tab更改key值刷新列表
    useEffect(() => {
        if (activeKey === '1') {
            fetchList({ pageNo: 1 });
        }
    }, [activeKey]);

    const tableRef = useRef();
    return (
        // <PageHeaderWrapper>
        <div>
            <CandidateSearchForm
                form={form}
                collapsed={collapsed}
                setCollapsed={setCollapsed}
                query={query}
                companyId={companyId}
                submit={handleSubmit}
                // submit={() => fetchList({ pageNo: 1 })}
                route={route}
            />

            <div ref={tableRef}>
                <Table
                    bordered={false}
                    scroll={{
                        // x: tableRef.current
                        //     ? tableRef.current.offsetWidth + 200
                        //     : '100%'
                        x: 1500
                    }}
                    columns={columns({
                        stageList,
                        scheduleList,
                        dispatch,
                        setVisible,
                        setentryVisible,
                        setCandicode,
                        setTalentCurent,
                        setRecruitCurent,
                        query,
                        candidateStage,
                        candidateState,
                        fetchList,
                        typeJump
                    })}
                    loading={loading.models.manage}
                    dataSource={tableData}
                    rowKey="myManageCandidate"
                    onChange={tableChange}
                    pagination={false}
                />
                <Pagination {...pagination} onChange={paginationChange} loading={loading.models.manage} />
            </div>
            <AddCandidate
                Visible={addVisible}
                params={{ companyId, fetchList }}
                // 关闭模态框
                onOk={() => setaddVisible(false)}
                onCancel={() => setaddVisible(false)}
            />

            <Filter
                Visible={visible}
                params={{
                    candidateCode: candicode,
                    companyId,
                    fetchList,
                    talentName: talentCurent,
                    recruitName: recruitCurent
                }}
                // 关闭模态框
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
            />
            <QuickEntry
                candidateCode={candicode}
                visible={entryVisible}
                onOk={() => {
                    setentryVisible(false);
                    fetchList({ pageNo: 1 });
                }}
                onCancel={() => setentryVisible(false)}
            />
        </div>
        // </PageHeaderWrapper>
    );
};
export default connect(({ manage, common, loading }) => ({
    manage,
    common,
    loading
}))(Form.create()(List));
